<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}
/*
 * 微信二维码处理类库
 */

class weixinScan {

    static public $rs = null; //记录集
    static public $uid = 0; //当前用户uid
    static public $isNewUser = false; //是否新用户，主要请于邀请模块

    /*
     * 初始化入口
     */

    static public function init($eventKey) {
        $res = null;
        self::getInfo($eventKey);
        if (!self::$rs) {
            return $res;
        }
        //根据相关类型进行处理
        switch (self::$rs['qmod']) {
            case 0://用户邀请
                $res = self::invite();
                break;
            case 1://51JhomePC网站
                $res = self::webCode();
                break;
            case 2://地推
                $res = self::spread();
                break;
            case 3://商家推广
                $res = self::business();
                break;
            case 4://小管家发券
                $res = self::stewardCoupon();
                break;
        }
        return $res ? $res : null; //无回调内容的请置空
    }

    /*
     * 根据key解析相关数据并处理
     */

    static public function getInfo($eventKey) {
        self::$rs = D('qrcode')->getQrcodeById($eventKey);
        return self::$rs;
    }

    /*
     * 处理用户邀请
     */

    static private function invite() {
       //saveLog('invite/info', array('rs' => self::$rs, 'uid' => self::$uid));
        $user = M('user')->field('username')->where(array('uid' => self::$uid))->find();
        if(isHave($user['username'])) {   //已注册返回
            return false;
        }
    //saveLog('invite/info', array('msg' => '更新用户信息', 'source_id' => 1, 'invite_uid' => self::$rs['uid']));
        return array('msg' => 0, 'id' => D('member')->update(array('invite_uid' => self::$rs['uid']), array('uid' => self::$uid)));
    }

    /*
     * 51Jhome网站进入
     */

    static private function webCode() {
//        saveLog('invite/webCode', array('rs' => self::$rs, 'uid' => self::$uid, 'isNewUser' => self::$isNewUser));
        if (!self::$isNewUser) {
//            saveLog('invite/webCode', '不是新用户，直接退出');
            return false;
        }
//        saveLog('invite/info', array('msg' => '更新用户信息', 'source_id' => 1, 'invite_uid' => self::$rs['uid']));
        return array('msg' => 0, 'id' => D('member')->update(array('source_id' => 2, 'invite_uid' => 1), array('uid' => self::$uid)));
    }

    /*
     * 固定小区
     */

    static private function spread() {
        if (!self::$isNewUser) {
//            saveLog('invite/spread', '不是新用户，直接退出');
            return false;
        }
        if (!isHave(self::$rs['info']['vid']) || !isHave(self::$rs['info']['invite_uid']) || !isHave(self::$rs['info']['city_id'])) {
//            saveLog('invite/spread_error', '不存在的key(vid\invite_uid\city_id)：' . self::$rs['info'] . '，直接退出');
            return false;
        }
//        saveLog('invite/info', array('msg' => '更新用户信息', 'source_id' => 1, 'invite_uid' => self::$rs['uid']));
        return array('msg' => 0, 'id' => D('member')->update(array('source_id' => 3, 'invite_uid' => self::$rs['info']['invite_uid'], 'city_id' => self::$rs['info']['city_id'], 'village_id' => self::$rs['info']['vid']), array('uid' => self::$uid)));
    }

    static private function business() {
        //后期用户输入商家特征码 再修改invite_uid
        D('member')->update(array('source_id' => 5, 'invite_uid' => 227), array('uid' => self::$uid));
        return array('msg' => "恭喜你得到一次领取优惠的机会！\n【<a href=\"http://wx.51jhome.com/weixin/user/bind.html?business=true\">领取优惠</a>】", 'id' => 0);
    }

    /*
     * 小管家领券,根据info中设定的参数来生成指定的券
     */

    static private function stewardCoupon() {
//        z(self::$rs);
//        saveLog('invite/stewardCoupon', self::$rs);
        //1、先判断时间是否可以领取
        if (self::$rs['info']['stime'] > TIME || self::$rs['info']['etime'] < TIME) {
            return array('msg' => '抱歉，当前时间不可领取', 'id' => 0);
        }
        //2、判断是否发放完毕
        if (D('steCoupon')->field('id')->where(array('stype' => self::$rs['info']['type'],
                    'smod' => self::$rs['scene_id'], 'city_id' => self::$rs['info']['city_id']))->count() >= self::$rs['info']['total']) {
            return array('msg' => '抱歉，优惠券已被抢光啦，下次早点来哦~', 'id' => 0);
        }
        //3、再判断当前用户是否可以领取
        if (D('steCoupon')->field('id')->where(array('stype' => self::$rs['info']['type'],
                    'used_uid' => self::$uid, 'smod' => self::$rs['scene_id'], 'city_id' => self::$rs['info']['city_id']))->count() >= self::$rs['info']['times']) {
            return array('msg' => '哎呀，您已经领过啦，不要太贪心哦~', 'id' => 0);
        }
        //3、根据实际配置信息去分配券
        $couponMoney = 0.00;
        $endTime = 0;
        $msg='';
        switch (self::$rs['scene_id']) {
            case 2977://指定生成新人券
                if (!self::$isNewUser) {
                    return array('msg' => '哎呀，新人券只有结邻公社新用户才能领取哦~', 'id' => 0);
                }
                $coupon = D('steCoupon')->field('COUNT(id) AS total,coupon_money')->where(array('stype' => 2, 'smod' => 2977, 'city_id' => self::$rs['info']['city_id']))->group('coupon_money')->findAll(false);
//                z(D('steCoupon')->getAllSql());
                //如果存在已发放的，就要在现有的基础上减去已发放的数量
//                z($coupon);
                if ($coupon) {
                    foreach ($coupon as $val) {
                        foreach (self::$rs['info']['item'] as $k => $v) {
                            //如果同金额的券发放已经达到上限
                            if ($val['coupon_money'] == $v['coupon_money'] && $val['total'] >= $v['count']) {
                                unset(self::$rs['info']['item'][$k]);
                            }
                        }
                    }
                }
                //防止设置的每个券的数量与总数量不一致导致数据为空
                if (!self::$rs['info']['item']) {
                    return array('msg' => '哎呀，您来晚了，抵价券已被抢光啦~', 'id' => 0);
                }
//                z(self::$rs['info']['item']);
                $rand = self::$rs['info']['item'][array_rand(self::$rs['info']['item'], 1)];
                $couponMoney = priceFormat($rand['coupon_money']);
                $endTime = self::$rs['info']['addtime'] * 60 * 60 * 24 + mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                if ($endTime > self::$rs['info']['end_time']) {
                    $endTime = self::$rs['info']['end_time'];
                }
                $msg='哇，运气真好~你收到了小管家派发的' . $couponMoney . "元新人红包！可在小管家快送栏目当现金使用哦！快去入住你的小区/写字楼使用吧\n\n<a href=\"" .
                U('weixin/user/coupon') . "\">查看我的红包</a>";
                break;
            case 2978://指定生成老用户满减券
                $rand = self::$rs['info']['item'][array_rand(self::$rs['info']['item'], 1)];
                $couponMoney = priceFormat($rand['coupon_money']);
                $endTime = self::$rs['info']['end_time'];
                $msg='恭喜您成功领取小管家' . $couponMoney . "元现金抵价券!\n\n<a href=\"" . U('steward/index/index') . "\">立即使用</a>\n\n<a href=\"" .
                U('weixin/user/coupon') . "\">查看我的抵价券</a>";
                break;
            default :
                return array('msg' => '没有找到相应信息', 'id' => 0);
        }
        $data = array(
            'stype' => self::$rs['info']['type'],
            'smod' => self::$rs['scene_id'],
            'city_id' => self::$rs['info']['city_id'],
            'coupon_title' => self::$rs['info']['coupon_title'],
            'coupon_code' => D('steCoupon')->getCouponCode(),
            'start_amount' => priceFormat(self::$rs['info']['start_amount']),
            'coupon_money' => $couponMoney,
            'used_uid' => self::$uid,
            'start_time' => self::$rs['info']['start_time'],
            'end_time' => $endTime, //outTime($endTime),
            'info_time' => TIME
        );
//        z($data);
        $id = D('steCoupon')->addPrizeCoupon($data);
        if ($id) {//
            return array('msg' => $msg, 'id' => $id);
        } else {
            return array('msg' => '抱歉，领取失败', 'id' => 0);
        }
    }

}
